package md.canvas;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

import md.action.EventController;
import md.action.GameController;
import md.constants.Constants;
import md.draw.GamePainter;
import md.settings.Settings;

public class MainGameCanvas extends GameCanvas implements Runnable {

	public static Thread thread;
	
	
	
	public MainGameCanvas() {
		super(true);
		Settings.init(getWidth(), getHeight());
		GameController.init();
	}
	
	protected void showNotify() {
		
	}
	
	protected void pointerPressed(int x, int y) {
		EventController.screenTouched(x, y);
	}
	
	private final void paint(Graphics g, int width, int height) {
		GamePainter.drawAll(g, width, height);
		flushGraphics();
	}
	
	public void run() {

		long time;
		final int timePerFrame = 1000 / Constants.FPS;
		
		Graphics g = getGraphics();
		int width = getWidth();
		int height = getHeight();
		
		time = System.currentTimeMillis();
		while(thread == Thread.currentThread()) {
			if(System.currentTimeMillis() - time >= timePerFrame) {
				GameController.calculateTurn();
				time = System.currentTimeMillis();
			}
			
			paint(g, width, height);
		
		}
		
	}
	
	public final void start() {
		thread = new Thread(this);
		thread.start();
	}
	
	public final void stop() {
		thread = null;
	}
	
}
